<template>
  <div class="block-list-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="searchParams" inline>
        <el-form-item label="举报人UID">
          <el-input
            v-model="searchParams.reporterUserNo"
            placeholder="请输入举报人UID"
            clearable
            style="width: 250px"
          />
        </el-form-item>

        <el-form-item label="被举报人UID">
          <el-input
            v-model="searchParams.reporteeNo"
            placeholder="请输入被举报人UID"
            clearable
            style="width: 250px"
          />
        </el-form-item>

        <el-form-item label="举报类型">
          <el-select
            v-model="searchParams.category"
            placeholder="请选择举报类型"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(item, key) in blockCategories"
              :key="key"
              :label="item.zh"
              :value="key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select
            v-model="searchParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 180px"
          >
            <el-option
              v-for="(text, value) in ReportStatusText"
              :key="value"
              :label="text"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 400px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            查询
          </el-button>
          <el-button @click="handleReset"> 重置 </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <template #header>
        <div class="card-header">
          <span>举报记录列表</span>
        </div>
      </template>

      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        stripe
        table-layout="auto"
      >
        <el-table-column
          prop="reporterUserNickname"
          label="举报人"
          min-width="120"
        >
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar
                :size="40"
                :src="row.reporterUserAvatar"
                @click="
                  handlePreviewAvatar(
                    row.reporterUserAvatar,
                    row.reporterUserNickname
                  )
                "
                class="clickable-avatar"
              />
              <div>
                <div class="user-no">ID：{{ row.reporterUserNo }}</div>
                <div class="nickname">{{ row.reporterUserNickname }}</div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="reporterUserNickname"
          label="被举报人"
          min-width="120"
        >
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar
                :size="40"
                :src="row.reporteeAvatar"
                @click="
                  handlePreviewAvatar(row.reporteeAvatar, row.reporteeName)
                "
                class="clickable-avatar"
              />
              <div>
                <div class="user-no">ID：{{ row.reporteeNo }}</div>
                <div class="nickname">{{ row.reporteeName }}</div>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="category" label="举报类型" min-width="140">
          <template #default="{ row }">
            <el-tag type="danger">
              {{ getBlockCategoryText(row.category) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="source"
          label="举报来源"
          min-width="120"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ ReportSourceText[row.source] }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="处理状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="ReportStatusType[row.status]">
              {{ ReportStatusText[row.status] }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column prop="reportTime" label="举报时间" min-width="140">
          <template #default="{ row }">
            {{ formatDateTime(row.reportTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="handledTime" label="处理时间" min-width="140">
          <template #default="{ row }">
            {{ formatDateTime(row.handledTime) }}
          </template>
        </el-table-column>

        <el-table-column
          prop="handlerUsername"
          label="最近操作人"
          min-width="100"
        >
          <template #default="{ row }">
            {{ row.handlerUsername ?? "-" }}
          </template>
        </el-table-column>

        <el-table-column label="操作" min-width="200" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons" v-if="row.status === 0">
              <el-button type="success" size="small" @click="handleIgnore(row)">
                <el-icon><Unlock /></el-icon>
                忽略
              </el-button>
              <el-button type="danger" size="small" @click="handleBlock(row)">
                <el-icon><Lock /></el-icon>
                处罚
              </el-button>
            </div>
            <div class="action-buttons" v-if="row.status === 1">
              <el-tag type="danger"> 已处罚 </el-tag>
            </div>
            <div class="action-buttons" v-if="row.status === 2">
              <el-tag type="primary"> 已忽略 </el-tag>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.pageIndex"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totals"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加封禁弹窗 -->
    <el-dialog
      v-model="blockDialogVisible"
      title="添加封禁"
      width="600px"
      :close-on-click-modal="false"
      @close="handleCancelBlock"
    >
      <el-form
        ref="blockFormRef"
        :model="blockForm"
        :rules="blockRules"
        label-width="120px"
      >
        <el-form-item label="用户ID" prop="userId">
          <el-input
            v-model="blockForm.userId"
            placeholder="请输入用户ID"
            clearable
            disabled
          />
        </el-form-item>

        <el-form-item label="用户昵称">
          <el-input v-model="currentUser.reporteeName" disabled />
        </el-form-item>

        <el-form-item label="封禁类型" prop="type">
          <el-select
            v-model="blockForm.type"
            placeholder="请选择封禁类型"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="(text, value) in blockTypes"
              :key="value"
              :label="text"
              :value="Number(value)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="封禁内容" prop="content">
          <el-input
            v-model="blockForm.content"
            placeholder="系统根据封禁类型自动填充"
            clearable
            disabled
          />
          <div v-if="blockForm.type === 1" class="form-tip">
            <el-tag type="info" size="small">账号封禁时自动填充用户ID</el-tag>
          </div>
          <div v-if="blockForm.type === 2" class="form-tip">
            <el-tag type="info" size="small">设备封禁时自动填充设备号</el-tag>
          </div>
          <div v-if="blockForm.type === 3" class="form-tip">
            <el-tag type="info" size="small">IP封禁时自动填充 0.0.0.0</el-tag>
          </div>
          <div v-if="blockForm.type === 4" class="form-tip">
            <el-tag type="info" size="small">房间封禁时自动填充用户编号</el-tag>
          </div>
        </el-form-item>

        <el-form-item label="封禁原因" prop="reasonCategory">
          <el-select
            v-model="blockForm.reasonCategory"
            placeholder="请选择封禁原因"
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="(item, key) in blockCategories"
              :key="key"
              :label="item.zh"
              :value="key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="封禁时长" prop="durationOfSeconds">
          <el-select
            v-model="blockForm.durationOfSeconds"
            placeholder="请选择封禁时长"
            style="width: 100%"
          >
            <el-option label="永久封禁" :value="-1" />
            <el-option label="1小时" :value="3600" />
            <el-option label="6小时" :value="21600" />
            <el-option label="1天" :value="86400" />
            <el-option label="3天" :value="259200" />
            <el-option label="7天" :value="604800" />
            <el-option label="30天" :value="2592000" />
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="blockForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（可选）"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancelBlock">取消</el-button>
          <el-button
            type="primary"
            :loading="blockLoading"
            @click="handleConfirmBlock"
          >
            确认封禁
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Unlock, Lock } from "@element-plus/icons-vue";
import {
  getBlockTypesApi,
  getBlockCategoriesApi,
  BlockTypesRes,
  BlockCategoriesRes,
  addBlockApi,
} from "@/api/block";
import {
  ReportStatusText,
  ReportStatusType,
  getReportPageApi,
  ReportRecordDto,
  ReportSearchReq,
  ReportSourceText,
  ignoreReportApi,
  BlockAddReq,
  punishLockReportApi,
} from "@/api/report";
import { UserInfo } from "@/api/user";

// 响应式数据
const loading = ref(false);
const tableData = ref<ReportRecordDto[]>([]);
const totals = ref(0);
const dateRange = ref<[string, string] | null>(null);
const blockTypes = ref<BlockTypesRes>({});
const blockCategories = ref<BlockCategoriesRes>({});

// 搜索参数
const searchParams = reactive<ReportSearchReq>({
  reporterUserNo: "", // 举报者用户编号
  reporteeNo: "", // 被举报者编号
  category: "", // 分类
  status: null, // 状态【0：待处理，1：已处理，2：忽略】
  source: null, // 举报信息类型，枚举【user：用户，room：房间】
  startTime: "",
  endTime: "",
  pageIndex: 1,
  pageSize: 10,
});

// 分页参数
const pagination = reactive({
  pageIndex: 1,
  pageSize: 10,
});

// 封禁相关
const blockDialogVisible = ref(false);
const blockLoading = ref(false);
const blockFormRef = ref();

const currentUser = ref<UserInfo>({} as UserInfo);

const blockForm = reactive<BlockAddReq>({
  userId: "",
  content: "",
  type: undefined,
  reasonCategory: "",
  remark: "",
  durationOfSeconds: 3600, // 默认1小时
});

// 封禁表单验证规则
const blockRules = {
  type: [{ required: true, message: "请选择封禁类型", trigger: "change" }],
  content: [
    {
      validator: (rule: any, value: any, callback: any) => {
        // 如果是IP封禁，不需要填写封禁内容
        if (blockForm.type === 3) {
          callback();
        } else if (blockForm.type === 1 || blockForm.type === 2) {
          // 账号封禁和设备封禁会自动填充内容，不需要验证
          callback();
        } else if (!value || value.trim() === "") {
          callback(new Error("请输入封禁内容"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  reasonCategory: [
    { required: true, message: "请选择封禁原因", trigger: "change" },
  ],
  durationOfSeconds: [
    { required: true, message: "请选择封禁时长", trigger: "change" },
  ],
};

// 加载数据
const loadData = async () => {
  loading.value = true;
  try {
    // 处理时间范围
    if (dateRange.value) {
      searchParams.startTime = convertToUTC(dateRange.value[0]);
      searchParams.endTime = convertToUTC(dateRange.value[1]);
    } else {
      searchParams.startTime = "";
      searchParams.endTime = "";
    }

    const response = await getReportPageApi(searchParams);
    tableData.value = response.data.list;
    totals.value = response.data.total;
  } catch (error) {
    console.error("加载封禁记录失败:", error);
    ElMessage.error("加载数据失败");
  } finally {
    loading.value = false;
  }
};

// 封禁用户
const handleBlock = (row: UserInfo) => {
  currentUser.value = row;
  blockForm.userId = row.reporteeNo;
  blockDialogVisible.value = true;
};

// 取消封禁
const handleCancelBlock = () => {
  blockDialogVisible.value = false;
  // 重置表单
  Object.assign(blockForm, {
    userId: "",
    content: "",
    type: undefined,
    reasonCategory: "",
    remark: "",
    durationOfSeconds: 3600,
  });
  // 清空当前用户信息
  currentUser.value = {} as UserInfo;
};

// 确认封禁
const handleConfirmBlock = async () => {
  if (!blockFormRef.value) return;

  try {
    await blockFormRef.value.validate();
    blockLoading.value = true;

    // 根据封禁类型处理封禁内容
    let content = blockForm.content;
    if (blockForm.type === 1) {
      // 账号封禁：使用用户ID
      content = currentUser.value.reporteeNo || "";
    } else if (blockForm.type === 2) {
      // 设备封禁：使用设备号
      content = currentUser.value.deviceNo || "";
    } else if (blockForm.type === 3) {
      // IP封禁：使用 0.0.0.0
      content = "0.0.0.0";
    }

    const requestData = {
      ...blockForm,
      content: content,
    };

    await punishLockReportApi(currentUser.value.reporteeNo, requestData);
    ElMessage.success("封禁成功");
    blockDialogVisible.value = false;

    // 刷新列表
    loadData();
  } catch (error) {
    console.error("封禁失败:", error);
    ElMessage.error("封禁失败");
  } finally {
    blockLoading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  searchParams.pageIndex = 1;
  pagination.pageIndex = 1;
  loadData();
};

// 重置
const handleReset = () => {
  searchParams.reporterUserNo = null;
  searchParams.reporteeNo = null;
  searchParams.category = null;
  searchParams.status = null;
  searchParams.source = null;
  dateRange.value = null;
  searchParams.startTime = "";
  searchParams.endTime = "";
  searchParams.pageIndex = 1;
  pagination.pageIndex = 1;
  loadData();
};

// 分页大小改变
const handleSizeChange = (size: number) => {
  searchParams.pageSize = size;
  pagination.pageSize = size;
  searchParams.pageIndex = 1;
  pagination.pageIndex = 1;
  loadData();
};

// 当前页改变
const handleCurrentChange = (page: number) => {
  searchParams.pageIndex = page;
  pagination.pageIndex = page;
  loadData();
};

// 忽略
const handleIgnore = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要忽略用户 ${row.reporterUserNickname} 的${getBlockCategoryText(
        row.category
      )}举报吗？`,
      "确认忽略",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    // 调用忽略接口
    await ignoreReportApi(row.reportId);
    ElMessage.success("忽略成功");

    // 刷新列表
    loadData();
  } catch (error) {
    if (error !== "cancel") {
      console.error("忽略失败:", error);
      ElMessage.error("忽略失败");
    }
  }
};

// 预览头像
const handlePreviewAvatar = (avatarUrl: string, nickname: string) => {
  if (!avatarUrl) {
    ElMessage.warning("暂无头像");
    return;
  }

  // 使用 Element Plus 的图片预览功能
  const h = ElMessageBox.alert;
  ElMessageBox.alert(
    `<div style="text-align: center;">
      <img src="${avatarUrl}" style="max-width: 100%; max-height: 400px; border-radius: 8px;" />
      <p style="margin-top: 10px; font-size: 16px; color: #666;">${nickname} 的头像</p>
    </div>`,
    "头像预览",
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: "关闭",
      customClass: "avatar-preview-dialog",
    }
  );
};

// 格式化日期时间
const formatDateTime = (dateTime: string) => {
  if (!dateTime) return "-";
  // 检查是否为永久封禁时间
  if (dateTime?.startsWith("9999-")) return "永久封禁";
  const date = new Date(dateTime);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
  });
};

// 转换为UTC时间
const convertToUTC = (localTime: string) => {
  if (!localTime) return "";
  const date = new Date(localTime);
  return date.toISOString();
};

// 获取封禁原因文本
const getBlockCategoryText = (category: string) => {
  const categoryData = blockCategories.value[category];
  if (categoryData) {
    return categoryData.zh; // 返回中文名称
  }
  return category || "未知原因";
};

// 加载封禁类型
const loadBlockTypes = async () => {
  try {
    const response = await getBlockTypesApi();
    blockTypes.value = response.data;
  } catch (error) {
    console.error("加载封禁类型失败:", error);
    ElMessage.error("加载封禁类型失败");
  }
};

// 加载封禁原因分类
const loadBlockCategories = async () => {
  try {
    const response = await getBlockCategoriesApi();
    blockCategories.value = response.data;
  } catch (error) {
    console.error("加载封禁原因分类失败:", error);
    ElMessage.error("加载封禁原因分类失败");
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadBlockTypes();
  loadBlockCategories();
  loadData();
});
</script>

<style scoped lang="less">
.block-list-container {
  padding: 20px;
  font-size: 16px; // 整体字号调整
  width: 100%;
  max-width: 100%;
  overflow-x: auto; // 添加横向滚动

  .search-card {
    margin-bottom: 20px;

    :deep(.el-form-item__label) {
      font-size: 14px;
    }

    :deep(.el-input__inner) {
      font-size: 14px;
    }

    :deep(.el-select .el-input__inner) {
      font-size: 14px;
    }

    :deep(.el-button) {
      font-size: 14px;
      padding: 12px 20px;
    }
  }

  .table-card {
    width: 100%;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 18px;
      font-weight: 600;

      .header-actions {
        display: flex;
        gap: 10px;

        .el-button {
          font-size: 16px;
          padding: 12px 20px;
        }
      }
    }

    :deep(.el-table) {
      font-size: 16px;
      width: 100% !important;
      min-width: 1070px; // 设置最小宽度，确保所有列都能显示

      .el-table__header {
        th {
          font-size: 16px;
          font-weight: 600;
          padding: 16px 8px;
        }
      }

      .el-table__body {
        td {
          font-size: 16px;
          padding: 16px 8px;
        }
      }

      .el-table__inner-wrapper {
        width: 100% !important;
      }

      .el-table__body-wrapper {
        width: 100% !important;
      }
    }

    :deep(.el-tag) {
      font-size: 14px;
      padding: 6px 12px;
    }
  }

  .user-info {
    display: flex;
    align-items: center;
    gap: 6px;

    .clickable-avatar {
      cursor: pointer;
      transition: transform 0.2s ease;
      flex-shrink: 0;

      &:hover {
        transform: scale(1.1);
      }
    }

    .nickname {
      font-weight: 500;
      font-size: 16px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
  }

  .action-buttons {
    display: flex;
    gap: 8px;
    align-items: center;
    justify-content: flex-start;
    // flex-wrap: wrap;

    .el-button {
      margin: 0;
      flex-shrink: 0;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;

    :deep(.el-pagination) {
      font-size: 16px;

      .el-pagination__total {
        font-size: 16px;
      }

      .el-pagination__sizes {
        .el-select .el-input__inner {
          font-size: 16px;
        }
      }

      .btn-prev,
      .btn-next {
        font-size: 16px;
      }

      .el-pager li {
        font-size: 16px;
      }
    }
  }
}

// 全局样式，用于头像预览对话框
:global(.avatar-preview-dialog) {
  .el-message-box__content {
    padding: 20px;
  }

  .el-message-box__message {
    margin: 0;
  }
}
</style>
